import ika
import controls

TIMER_MAX_FRAME_GAP = 3

TIMER_SPEED_NORMAL, TIMER_SPEED_FAST_FORWARD, TIMER_SPEED_SLOW_MOTION = range(3)

class Timer(object):
    def __init__ (self):
        self.tick_last = ika.GetTime()
        self.second_last = 0
        self.gap = 0
        self.fractional_gap = 0
        self.update_count = 0
        self.frame_rate = 0
        self.speed = TIMER_SPEED_NORMAL
            
    def Input(self, held, pressed):
        if "ffwd" in held:
            self.speed = TIMER_SPEED_FAST_FORWARD
        elif "slow" in held:
            self.speed = TIMER_SPEED_SLOW_MOTION
        else:
            self.speed = TIMER_SPEED_NORMAL
        
    def Update(self):
        self.update_count += 1      
        if ika.GetTime() - self.second_last > 99:
            self.frame_rate = self.update_count
            self.update_count = 0
            self.second_last = ika.GetTime()
            #ika.SetCaption("FPS: " + str(self.frameRate) + " " + str(ika.GetFrameRate()))
        if ika.GetTime() - self.tick_last > 0:
            self.gap = ika.GetTime() - self.tick_last
            if self.fractional_gap >= 1:
                self.gap += int(self.fractional_gap)
                self.fractional_gap = 0
            if self.speed == TIMER_SPEED_FAST_FORWARD:
                self.gap *= 4.0   
            elif self.speed == TIMER_SPEED_SLOW_MOTION:
                self.gap /= 2.0
                self.fractional_gap += int(self.gap) - self.gap
            
            if self.speed != TIMER_SPEED_FAST_FORWARD:
                self.gap = min(TIMER_MAX_FRAME_GAP, int(self.gap))
            self.tick_last = ika.GetTime()
        else:
            self.gap = 0